<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0,viewport-fit=cover"><title>class中的state和hooks中的state | 刘超的博客</title><meta name="author" content="刘超"><meta name="copyright" content="刘超"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="类组件中的 statesetState 的用法 基本用法 setState(obj,callback)  &emsp;第一个参数:当 obj 为对象,即为即将合并的 state;如果 obj 是一个函数,那么当前组件的 state 和 props 将作为参数,返回新的 state,&emsp;第二个参数 callback:callback 作为一个函数,函数执行上下文中获取当前更新的 setSta">
<meta property="og:type" content="article">
<meta property="og:title" content="class中的state和hooks中的state">
<meta property="og:url" content="https://leachliu.gitee.io/2021/12/30/react/class%E4%B8%AD%E7%9A%84state%E5%92%8Chooks%E4%B8%AD%E7%9A%84state/index.html">
<meta property="og:site_name" content="刘超的博客">
<meta property="og:description" content="类组件中的 statesetState 的用法 基本用法 setState(obj,callback)  &emsp;第一个参数:当 obj 为对象,即为即将合并的 state;如果 obj 是一个函数,那么当前组件的 state 和 props 将作为参数,返回新的 state,&emsp;第二个参数 callback:callback 作为一个函数,函数执行上下文中获取当前更新的 setSta">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://leachliu.gitee.io/images/avatar.webp">
<meta property="article:published_time" content="2021-12-29T16:00:00.000Z">
<meta property="article:modified_time" content="2023-11-03T07:37:06.441Z">
<meta property="article:author" content="刘超">
<meta property="article:tag" content="state">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://leachliu.gitee.io/images/avatar.webp"><link rel="shortcut icon" href="/images/favicon.ico"><link rel="canonical" href="https://leachliu.gitee.io/2021/12/30/react/class%E4%B8%AD%E7%9A%84state%E5%92%8Chooks%E4%B8%AD%E7%9A%84state/index.html"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox/fancybox.min.css" media="print" onload="this.media='all'"><script>const GLOBAL_CONFIG = {
  root: '/',
  algolia: {"appId":"VFZO06XK8A","apiKey":"1202cec78a85d208874b3c9cbcd0e212","indexName":"index total","hits":{"per_page":10},"languages":{"input_placeholder":"搜索文章","hits_empty":"找不到您查询的内容：${query}","hits_stats":"找到 ${hits} 条结果，用时 ${time} 毫秒"}},
  localSearch: undefined,
  translate: undefined,
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":false},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '',
  dateSuffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: undefined,
  lightbox: 'fancybox',
  Snackbar: undefined,
  infinitegrid: {
    js: 'https://cdn.jsdelivr.net/npm/@egjs/infinitegrid/dist/infinitegrid.min.js',
    buttonText: '加载更多'
  },
  isPhotoFigcaption: false,
  islazyload: false,
  isAnchor: false,
  percent: {
    toc: true,
    rightside: false,
  },
  autoDarkmode: false
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: 'class中的state和hooks中的state',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2023-11-03 15:37:06'
}</script><script>(win=>{
      win.saveToLocal = {
        set: (key, value, ttl) => {
          if (ttl === 0) return
          const now = Date.now()
          const expiry = now + ttl * 86400000
          const item = {
            value,
            expiry
          }
          localStorage.setItem(key, JSON.stringify(item))
        },
      
        get: key => {
          const itemStr = localStorage.getItem(key)
      
          if (!itemStr) {
            return undefined
          }
          const item = JSON.parse(itemStr)
          const now = Date.now()
      
          if (now > item.expiry) {
            localStorage.removeItem(key)
            return undefined
          }
          return item.value
        }
      }
    
      win.getScript = (url, attr = {}) => new Promise((resolve, reject) => {
        const script = document.createElement('script')
        script.src = url
        script.async = true
        script.onerror = reject
        script.onload = script.onreadystatechange = function() {
          const loadState = this.readyState
          if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
          script.onload = script.onreadystatechange = null
          resolve()
        }

        Object.keys(attr).forEach(key => {
          script.setAttribute(key, attr[key])
        })

        document.head.appendChild(script)
      })
    
      win.getCSS = (url, id = false) => new Promise((resolve, reject) => {
        const link = document.createElement('link')
        link.rel = 'stylesheet'
        link.href = url
        if (id) link.id = id
        link.onerror = reject
        link.onload = link.onreadystatechange = function() {
          const loadState = this.readyState
          if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
          link.onload = link.onreadystatechange = null
          resolve()
        }
        document.head.appendChild(link)
      })
    
      win.activateDarkMode = () => {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = () => {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
        if (t === 'dark') activateDarkMode()
        else if (t === 'light') activateLightMode()
      
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
      const detectApple = () => {
        if(/iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
          document.documentElement.classList.add('apple')
        }
      }
      detectApple()
    })(window)</script><link rel="stylesheet" href="https://npm.elemecdn.com/ethan4116-blog/lib/css/plane_v2.css"><link rel="stylesheet" href="https://fastly.jsdelivr.net/gh/l-lin/font-awesome-animation/dist/font-awesome-animation.min.css"  media="defer" onload="this.media='all'"><script defer src="/js/custom.js"></script><link rel="stylesheet" href="https://fastly.jsdelivr.net/gh/HCLonely/images@master/others/heartbeat.min.css"><link rel="stylesheet" href="/css/universe.css"><link rel="stylesheet" href="/css/custom.css"><!-- hexo injector head_end start --><link rel="stylesheet" href="https://npm.elemecdn.com/hexo-butterfly-tag-plugins-plus@latest/lib/assets/font-awesome-animation.min.css" media="defer" onload="this.media='all'"><link rel="stylesheet" href="https://npm.elemecdn.com/hexo-butterfly-tag-plugins-plus@latest/lib/tag_plugins.css" media="defer" onload="this.media='all'"><script src="https://npm.elemecdn.com/hexo-butterfly-tag-plugins-plus@latest/lib/assets/carousel-touch.js"></script><!-- hexo injector head_end end --><meta name="generator" content="Hexo 7.0.0"></head><body><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src="/images/avatar.webp" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="sidebar-site-data site-data is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">41</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">21</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">6</div></a></div><hr class="custom-hr"/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 时间轴</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="not-top-img" id="page-header"><nav id="nav"><span id="blog-info"><a href="/" title="刘超的博客"><span class="site-name">刘超的博客</span></a></span><div id="menus"><div id="search-button"><a class="site-page social-icon search" href="javascript:void(0);"><i class="fas fa-search fa-fw"></i><span> 搜索</span></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 时间轴</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div></div><div id="toggle-menu"><a class="site-page" href="javascript:void(0);"><i class="fas fa-bars fa-fw"></i></a></div></div></nav></header><main class="layout" id="content-inner"><div id="post"><div id="post-info"><h1 class="post-title">class中的state和hooks中的state</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2021-12-29T16:00:00.000Z" title="发表于 2021-12-30 00:00:00">2021-12-30</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2023-11-03T07:37:06.441Z" title="更新于 2023-11-03 15:37:06">2023-11-03</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/react/">react</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="class中的state和hooks中的state"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">阅读量:</span><span id="busuanzi_value_page_pv"><i class="fa-solid fa-spinner fa-spin"></i></span></span></div></div></div><article class="post-content" id="article-container"><h2 id="类组件中的-state"><a href="#类组件中的-state" class="headerlink" title="类组件中的 state"></a>类组件中的 state</h2><h3 id="setState-的用法"><a href="#setState-的用法" class="headerlink" title="setState 的用法"></a>setState 的用法</h3><ul>
<li><p>基本用法</p>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="title function_">setState</span>(obj,callback)</span><br></pre></td></tr></table></figure></li>
</ul>
<p>&emsp;第一个参数:当 obj 为<font color="red">对象</font>,即为即将合并的 state;如果 obj 是一个<font color="red">函数</font>,那么当前组件的 state 和 props 将作为参数,返回新的 state,<br>&emsp;第二个参数 callback:callback 作为一个函数,函数执行上下文中获取当前更新的 setState 值(箭头函数创建了新的执行上下文环境,获取到更新之后的值),可以作为依赖 state 的副作用函数,可以用更新之后的数据进行一些 DOM 操作</p>
  <figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="comment">//第一个参数为函数类型</span></span><br><span class="line"><span class="variable language_">this</span>.<span class="title function_">setState</span>(<span class="function">(<span class="params">state,props</span>)=&gt;</span>&#123;</span><br><span class="line">  <span class="keyword">return</span> &#123; number : <span class="number">1</span> &#125;</span><br><span class="line">&#125;)</span><br><span class="line"><span class="comment">//合并的state  可以理解为&#123;...state,...newState&#125;</span></span><br><span class="line"></span><br><span class="line"><span class="comment">//第一个参数为对象时</span></span><br><span class="line"><span class="variable language_">this</span>.<span class="title function_">setState</span>(&#123;<span class="attr">number</span>:<span class="number">1</span>&#125;,<span class="function">()=&gt;</span>&#123;</span><br><span class="line">    <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="variable language_">this</span>.<span class="property">state</span>.<span class="property">number</span>)  <span class="comment">//获取最新的number值</span></span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>

<h3 id="假设一件事件中触发了一次如上-setState-在-React-底层到底做了写什么事情"><a href="#假设一件事件中触发了一次如上-setState-在-React-底层到底做了写什么事情" class="headerlink" title="假设一件事件中触发了一次如上 setState,在 React 底层到底做了写什么事情?"></a>假设一件事件中触发了一次如上 setState,在 React 底层到底做了写什么事情?</h3><ul>
<li>首先setState 会产生当前<font color="red">更新的优先级</font>(老版本用 expirationTime,新版本用 lane)</li>
<li>接下来 React 会从 fiber Root 根部 fiber 向下调和子节点,调和阶段将对比发生更新的地方,更新对比 expirationTime,找到发生更新的组件,合并 state,然后触发 render 函数渲染,得到新的 UI 视图层,完成 render 阶段</li>
<li>接下来到 commit 阶段,commit 阶段替换真实 DOM,完成此次流程更新</li>
<li>此时仍然在 commit 阶段,会执行 setState 中 callback 函数的,如上的<font color="red">() &#x3D;&gt; {console.log(this.number)}</font>,到此为止完成了一次 setState 的完整流程</li>
</ul>
<p><img src=""></p>
<p>&emsp;请记住一个主要任务的先后顺序,这对于弄清渲染可能有所帮助 render 阶段 render 函数执行 -&gt; commit 阶段真实 DOM 替换 -&gt; setState 函数执行回调</p>
<h3 id="类组件如何限制-state-更新视图"><a href="#类组件如何限制-state-更新视图" class="headerlink" title="类组件如何限制 state 更新视图"></a>类组件如何限制 state 更新视图</h3>  <h4>对于类组件如何限制state更新作用呢?</h4>
  
<ul>
<li>pureComponent可以对state和props进行浅比较,如果不发生变化,则不进行更新</li>
<li>shouldComponentUpdate生命周期可以判断前后state来决定组件是否进行更新,更新返回true,否则返回false</li>
</ul>
<h2 id="setState-原理"><a href="#setState-原理" class="headerlink" title="setState 原理"></a>setState 原理</h2><p>&emsp;调用 setState 方法,实际上是 React 底层调用 Updater 对象上的 enqueueSetState 的方法,要弄明白 setState 更新机制,从 2 个方面分析</p>
<ul>
<li>是解密 enqueueSetState 到底是做了写什么</li>
<li>是 React 底层到底如何进行的批量更新</li>
</ul>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line">react-reconciler/src/<span class="title class_">ReactFiberClassComponent</span>.<span class="property">js</span></span><br></pre></td></tr></table></figure>

<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="title function_">enqueueSetState</span>(<span class="params"></span>)&#123;</span><br><span class="line">  <span class="comment">//每一次调用setState,react都会创建一个update里面保存了</span></span><br><span class="line">  <span class="keyword">const</span> update = <span class="title function_">createUpdate</span>(experiationTime,suspenseCinfig);</span><br><span class="line">  <span class="comment">// callBack可以理解为setState的回调函数,第二个参数</span></span><br><span class="line">  callback &amp;&amp; (update.<span class="property">callback</span> = callback)</span><br><span class="line">  <span class="comment">/* enqueueUpdate 把当前的update 传入当前fiber，待更新队列中 */</span></span><br><span class="line">  <span class="title function_">enqueueUpdate</span>(fiber, update);</span><br><span class="line">  <span class="comment">//开始调度更新 这是个重点会在下面的内容讲到他的作用</span></span><br><span class="line">  <span class="title function_">scheuduleUpdateOnFiber</span>(fiber,expirationTime);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>&emsp;enqueueSetState 作用实际很简单,就是创建一个 update,然后放入当前 fiber 对象待更新队列中,最后开启调度更新,进入上述过程<br>&emsp;我们在进行 setState 更新都是通过触发事件,React 是采用事件合成的形式,每一个事件都是由 React 事件系统统一调度,那么 State 批量更新正是和事件系统息息相关</p>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="comment">/* 在`legacy`模式下，所有的事件都将经过此函数同一处理 */</span></span><br><span class="line"><span class="keyword">function</span> <span class="title function_">dispatchEventForLegacyPluginEventSystem</span>(<span class="params"></span>) &#123;</span><br><span class="line">  <span class="comment">// handleTopLevel 事件处理函数</span></span><br><span class="line">  <span class="title function_">batchedEventUpdates</span>(handleTopLevel, bookKeeping);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="comment">//重点就是这个batchEventUpdates</span></span><br><span class="line"><span class="keyword">function</span> <span class="title function_">batchEventUpdates</span>(<span class="params">fn,a</span>)&#123;</span><br><span class="line">  <span class="comment">//开启批量更新</span></span><br><span class="line">  isBatchingEventUpdates = <span class="literal">true</span>;</span><br><span class="line">  <span class="keyword">try</span>&#123;</span><br><span class="line">    <span class="comment">//这里执行了事件处理函数</span></span><br><span class="line">    <span class="comment">// 在setTimeout Promise中 原生事件中事件循环下一轮 此时 isBatchEventUpdates为false</span></span><br><span class="line">   <span class="keyword">return</span> <span class="title function_">batchEventUpdatesImpl</span>(fn,a,b);</span><br><span class="line">  &#125;<span class="keyword">finally</span>&#123;</span><br><span class="line">   isBatchingEventUpdates = <span class="literal">false</span></span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>&emsp;如上可以分析流程,在 React 事件执行之前通过<font color="red">isBatchingEventUpdates &#x3D; true</font>打开开关,开启事件批量更新,当事件结束,再通过 isBatchingEventUpdates &#x3D; false 关闭开关,然后在 scheduleUpdateOnFiber 中判断是否需要批量更新,<font color="red" size="3">新版本 React17 以后,不再依靠 isBatchingEventUpdates 来判断是否更新,而是依靠执行上下文。下面会有详细的解释</font></p>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="comment">//事件触发 setState调用enqueueSetState</span></span><br><span class="line"><span class="comment">//而scheuduleUpdateOnFiber来根据这个开关来判断是否进行批量更新</span></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">function</span> <span class="title function_">scheduleUpdateOnFiber</span>(<span class="params">fiber,lane,eventTime</span>)&#123;</span><br><span class="line">  <span class="keyword">if</span>(lane === <span class="title class_">SycLane</span>)&#123;</span><br><span class="line">    <span class="keyword">if</span>(</span><br><span class="line">      <span class="comment">//这里的LegacyUnbachedContext 就是指的isBatchEventUpdates 来判断是否批量更新</span></span><br><span class="line">      (executionContext &amp;&amp; <span class="title class_">LegacyUnbachedContext</span>) !== <span class="title class_">NoContext</span> &amp;&amp;</span><br><span class="line">      (executionContext &amp;&amp; (<span class="title class_">RenderContext</span> | <span class="title class_">CommitContext</span>) === <span class="title class_">NoContext</span>)&#123;</span><br><span class="line">        <span class="comment">//开启同步更新 进入到workloop流程</span></span><br><span class="line">        <span class="title function_">performSyncWorkOnRoot</span>(root)</span><br><span class="line">      &#125;<span class="keyword">else</span>&#123;</span><br><span class="line">        <span class="comment">/* 进入调度,把任务放入调度*/</span></span><br><span class="line">        <span class="title function_">ensureRootIsSheduled</span>(root,eventTime);</span><br><span class="line">        <span class="keyword">if</span>(executionContext === <span class="title class_">NoContext</span>)&#123;</span><br><span class="line">          <span class="comment">/*当前的执行任务类型为NoContext 说明任务是非可控的 调用flushSyncCallbackQueue  立即执行*/</span></span><br><span class="line">          <span class="title function_">flushSyncCallbackQueue</span>();</span><br><span class="line">        &#125;</span><br><span class="line">      &#125;</span><br><span class="line">    )</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>&emsp;scheduleUpdateOnFiber 的核心逻辑如上,正常情况,大多数任务都是<font color="red">SyncLane</font>。即便在异步任务里面触发更新,比如是<font color="red">Promise</font>或者<font color="red">setTimeout</font>里面的更新,也是 SycLane,两者之间没有太大的联系。</p>
<p>在<font color="red">scheduleUpdateOnFiber</font>内部的主要做的事情是:</p>
<ul>
<li>在<font color="red">unbatch(指初始化渲染的时候)</font>的情况,初始化的更新会通过 unbatchedUpdates 包裹,<font color="red" size="3">那么初始化的更新会直接进入调和阶段同步更新,而不会放入到调度任务中</font>,会直接进入 performSyncOnRoot,接下来进入调和阶段,就是<font color="red">render</font>,<font color="red">commit</font></li>
<li>那么任务是<font color="red">useState</font>和<font color="red">setState</font>,那么会进入<font color="red">else</font>流程,那么会进入<font color="red">ensureRootIsSheduled</font>调度流程。</li>
<li>当前执行的任务类型为<font color="red">NoContext</font>,说明当前任务是非可控的,那么会调用<font color="red">flushSyncCallbackQueue</font></li>
</ul>
<h2 id="legacy模式下的可控任务和非控任务"><a href="#legacy模式下的可控任务和非控任务" class="headerlink" title="legacy模式下的可控任务和非控任务"></a><font color="red">legacy</font>模式下的可控任务和非控任务</h2><ul>
<li>可控任务: React 事件系统中发生的任务,会被标记<font color="red">EventContext</font>,在<font>batchUpdate api</font>里面的更新任务,会被标记成<font color="red">BatchedContext</font>,那么这些任务是 React 可以检测到的,所以<font color="red">executionContext !&#x3D;&#x3D; NoContext</font>,那么不会执行<font color="red">flushSyncCallbackQueue</font></li>
<li>不可控任务: 如果在<font color="black" size="3">如果在延时器(Timer)队列</font>或者是<font>微任务队列(microtask)</font>,那么这种任务更新任务,React 是无法控制执行时机的,所以<font color="red"> exexutionContext &#x3D;&#x3D;&#x3D; NoContext</font>那么会立即执行<font color="red">flushSyncCallbackQueue</font></li>
</ul>
<p>&emsp;举例</p>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> <span class="keyword">class</span> <span class="title class_">Index</span> <span class="keyword">extends</span> <span class="title class_ inherited__">React.Component</span>&#123;</span><br><span class="line">    <span class="attr">state</span>:&#123; number : <span class="number">0</span> &#125;</span><br><span class="line">    handleClick = <span class="function">() =&gt;</span> &#123;</span><br><span class="line">      <span class="variable language_">this</span>.<span class="title function_">setState</span>(&#123;<span class="attr">number</span>:<span class="variable language_">this</span>.<span class="property">state</span>.<span class="property">number</span>+<span class="number">1</span> &#125;,<span class="function">()=&gt;</span>&#123;</span><br><span class="line">        <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&#x27;callback1&#x27;</span>,<span class="variable language_">this</span>.<span class="property">state</span>.<span class="property">number</span>)</span><br><span class="line">      &#125;)</span><br><span class="line">        <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="variable language_">this</span>.<span class="property">state</span>.<span class="property">number</span>)</span><br><span class="line">      <span class="variable language_">this</span>.<span class="title function_">setState</span>(&#123;<span class="attr">number</span>:<span class="variable language_">this</span>.<span class="property">state</span>.<span class="property">number</span>+<span class="number">1</span> &#125;,<span class="function">()=&gt;</span>&#123;</span><br><span class="line">        <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&#x27;callback2&#x27;</span>,<span class="variable language_">this</span>.<span class="property">state</span>.<span class="property">number</span>)</span><br><span class="line">      &#125;)</span><br><span class="line">        <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="variable language_">this</span>.<span class="property">state</span>.<span class="property">number</span>)</span><br><span class="line">      <span class="variable language_">this</span>.<span class="title function_">setState</span>(&#123;<span class="attr">number</span>:<span class="variable language_">this</span>.<span class="property">state</span>.<span class="property">number</span>+<span class="number">1</span> &#125;,<span class="function">()=&gt;</span>&#123;</span><br><span class="line">        <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&#x27;callback3&#x27;</span>,<span class="variable language_">this</span>.<span class="property">state</span>.<span class="property">number</span>)</span><br><span class="line">      &#125;)</span><br><span class="line">        <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="variable language_">this</span>.<span class="property">state</span>.<span class="property">number</span>)</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="title function_">render</span>(<span class="params"></span>)&#123;</span><br><span class="line">      <span class="keyword">return</span>(</span><br><span class="line">        &lt;div&gt;</span><br><span class="line">           &#123;<span class="variable language_">this</span>.<span class="property">state</span>.<span class="property">number</span>&#125;</span><br><span class="line">          &lt;button onClick=&#123;<span class="variable language_">this</span>.<span class="property">handleClick</span>&#125;&gt;number ++&lt;button&gt;</span><br><span class="line">        &lt;div&gt;</span><br><span class="line">      )</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>&emsp;点击打印,打印结果为 0,0,0,1,callback1,callback2,callback3<br>&emsp;如上代码,在整个上下文执行栈中会变成这样:<br><img src=""></p>
<p>&emsp;为什么异步操作里面的批量更新规则被打破呢?比如用 promise 或者 setTimeout 在 handleClick 中这样写</p>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="built_in">setTimeout</span>(<span class="function">()=&gt;</span>&#123;</span><br><span class="line">   <span class="variable language_">this</span>.<span class="title function_">setState</span>(&#123;<span class="attr">number</span>:<span class="variable language_">this</span>.<span class="property">state</span>.<span class="property">number</span>+<span class="number">1</span> &#125;,<span class="function">()=&gt;</span>&#123;</span><br><span class="line">     <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&#x27;callback1&#x27;</span>,<span class="variable language_">this</span>.<span class="property">state</span>.<span class="property">number</span>)</span><br><span class="line">   &#125;)</span><br><span class="line">   <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="variable language_">this</span>.<span class="property">state</span>.<span class="property">number</span>)</span><br><span class="line">   <span class="variable language_">this</span>.<span class="title function_">setState</span>(&#123;<span class="attr">number</span>:<span class="variable language_">this</span>.<span class="property">state</span>.<span class="property">number</span>+<span class="number">1</span> &#125;,<span class="function">()=&gt;</span>&#123;</span><br><span class="line">   <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&#x27;callback2&#x27;</span>,<span class="variable language_">this</span>.<span class="property">state</span>.<span class="property">number</span>)</span><br><span class="line">   &#125;)</span><br><span class="line">     <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="variable language_">this</span>.<span class="property">state</span>.<span class="property">number</span>)</span><br><span class="line">   <span class="variable language_">this</span>.<span class="title function_">setState</span>(&#123;<span class="attr">number</span>:<span class="variable language_">this</span>.<span class="property">state</span>.<span class="property">number</span>+<span class="number">1</span> &#125;,<span class="function">()=&gt;</span>&#123;</span><br><span class="line">     <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&#x27;callback3&#x27;</span>,<span class="variable language_">this</span>.<span class="property">state</span>.<span class="property">number</span>)</span><br><span class="line">   &#125;)</span><br><span class="line">   <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="variable language_">this</span>.<span class="property">state</span>.<span class="property">number</span>)</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>

<p>&emsp;打印的结果为<font face="黑体" color="Black" size="3">callback1 1,callback2 2,callback3 3</font><br>&emsp;那么在整个执行上下文栈中就变成如下图这样:<br><img src=""><br><font color="black"><h4>所以批量更新规则被打破。</h4></font><br><font color="black"><h4>那么如何在异步环境下,继续开启批量更新模式</h4></font><br>&emsp;react-dom 中提供了批量更新的方法<font>unstable_batchUpdates</font>可以手动批量更新。</p>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="built_in">setTimeout</span>(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">  <span class="title function_">unstable_batchUpdates</span>(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">    <span class="variable language_">this</span>.<span class="title function_">setState</span>(&#123; <span class="attr">number</span>: <span class="variable language_">this</span>.<span class="property">state</span>.<span class="property">number</span> + <span class="number">1</span> &#125;, <span class="function">() =&gt;</span> &#123;</span><br><span class="line">      <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&quot;callback1&quot;</span>, <span class="variable language_">this</span>.<span class="property">state</span>.<span class="property">number</span>);</span><br><span class="line">    &#125;);</span><br><span class="line">    <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="variable language_">this</span>.<span class="property">state</span>.<span class="property">number</span>);</span><br><span class="line">    <span class="variable language_">this</span>.<span class="title function_">setState</span>(&#123; <span class="attr">number</span>: <span class="variable language_">this</span>.<span class="property">state</span>.<span class="property">number</span> + <span class="number">1</span> &#125;, <span class="function">() =&gt;</span> &#123;</span><br><span class="line">      <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&quot;callback2&quot;</span>, <span class="variable language_">this</span>.<span class="property">state</span>.<span class="property">number</span>);</span><br><span class="line">    &#125;);</span><br><span class="line">    <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="variable language_">this</span>.<span class="property">state</span>.<span class="property">number</span>);</span><br><span class="line">    <span class="variable language_">this</span>.<span class="title function_">setState</span>(&#123; <span class="attr">number</span>: <span class="variable language_">this</span>.<span class="property">state</span>.<span class="property">number</span> + <span class="number">1</span> &#125;, <span class="function">() =&gt;</span> &#123;</span><br><span class="line">      <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&quot;callback3&quot;</span>, <span class="variable language_">this</span>.<span class="property">state</span>.<span class="property">number</span>);</span><br><span class="line">    &#125;);</span><br><span class="line">    <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="variable language_">this</span>.<span class="property">state</span>.<span class="property">number</span>);</span><br><span class="line">  &#125;);</span><br><span class="line">  <span class="comment">//这样打印结果就和最开始不使用定时器的结果一样呢</span></span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>

<p>&emsp;<font>flushSync</font>可以将回调函数中的更新任务,放在一个较高的优先级中。</p>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line">handleClick = <span class="function">() =&gt;</span> &#123;</span><br><span class="line">  <span class="built_in">setTimeout</span>(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">    <span class="variable language_">this</span>.<span class="title function_">setState</span>(&#123; <span class="attr">number</span>: <span class="number">1</span> &#125;);</span><br><span class="line">  &#125;);</span><br><span class="line">  <span class="variable language_">this</span>.<span class="title function_">setState</span>(&#123; <span class="attr">number</span>: <span class="number">2</span> &#125;);</span><br><span class="line">  <span class="title class_">ReactDom</span>.<span class="title function_">flushSync</span>(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">    <span class="variable language_">this</span>.<span class="title function_">setState</span>(&#123; <span class="attr">number</span>: <span class="number">3</span> &#125;);</span><br><span class="line">  &#125;);</span><br><span class="line">  <span class="variable language_">this</span>.<span class="title function_">setState</span>(&#123; <span class="attr">number</span>: <span class="number">4</span> &#125;);</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>

<p>&emsp;打印结果<font color="black" size="3">3 , 4 , 1</font>。<br>&emsp;首先<font color="red" size="3">flushSync this.setState({number : 3})</font>提高了一个较高的优先级,所以 2 和 3 被批量更新,flushSync 提高优先级 但是之前低优先级的位置顺序并不发生变化,所以为 3。<br>&emsp;普通优先级为 4。<br>&emsp;最后 setTimeout 中的 number 为 1;</p>
<p><font color="black" size="3">flushSync 补充说明:</font>flushSync 在同步条件下会合并之前的 state|useState,可以理解成,如果发现了 flushSync,就会立即执行更新</p>
<p>&emsp;综上所述:React 统一级别更新的<font color="black" size="3">优先级</font>关系是:<br>&emsp;flushSync 中的 SetState &gt; 正常执行上下文中的 setState &gt; setTimeout,Promise 中的 setState</p>
<h2 id="函数组件中的-state"><a href="#函数组件中的-state" class="headerlink" title="函数组件中的 state"></a>函数组件中的 state</h2><h3 id="useStete-的用法"><a href="#useStete-的用法" class="headerlink" title="useStete 的用法"></a>useStete 的用法</h3><h4 id="基本用法"><a href="#基本用法" class="headerlink" title="基本用法"></a>基本用法</h4><figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line">[state, dispatch] = <span class="title class_">React</span>.<span class="title function_">useState</span>(initData);</span><br></pre></td></tr></table></figure>

<ul>
<li>state,目的提供给 UI,作为渲染视图的数据源。</li>
<li>dispatch 改变 state 的函数,可以理解为推动函数组件渲染的函数。</li>
<li>initData 有两种情景,第一种是非函数,将作为 state 的初始值。第二种情况是函数,函数的返回值是初始值</li>
</ul>
<p>&emsp;initData 为非函数的情况</p>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="comment">/* 此时将0作为初始值 */</span></span><br><span class="line"><span class="keyword">const</span> [number, setNumber] = <span class="title class_">React</span>.<span class="title function_">useState</span>(<span class="number">0</span>);</span><br></pre></td></tr></table></figure>

<p>&emsp;initData 为函数的情况</p>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="keyword">const</span> [number, setNumber] = <span class="title class_">React</span>.<span class="title function_">useState</span>(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">  <span class="keyword">return</span> <span class="title class_">Math</span>.<span class="title function_">random</span>();</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>

<p>&emsp; dispatch 也有两种情况</p>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="comment">/* dispatch参数是一个非函数值 */</span></span><br><span class="line">handleClick = <span class="function">() =&gt;</span> &#123;</span><br><span class="line">  <span class="title function_">setNumberr</span>(<span class="number">0</span>);</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="comment">/* dispatch参数是一个函数 */</span></span><br><span class="line"><span class="title function_">setNumber</span>(<span class="function">(<span class="params">number</span>) =&gt;</span> number + <span class="number">1</span>);</span><br></pre></td></tr></table></figure>

<h2 id="如何监听-state-变化"><a href="#如何监听-state-变化" class="headerlink" title="如何监听 state 变化"></a>如何监听 state 变化</h2><p>&emsp;需要使用 useEffect 钩子函数,通常可以把 state 作为依赖项传入 useEffect 的第二个参数 deps</p>
<h2 id="dispatch更新特点"><a href="#dispatch更新特点" class="headerlink" title="dispatch更新特点"></a><font color="red">dispatch</font>更新特点</h2><p>&emsp;上述讲的批量更新和 flushSync,在函数组件中,dispatch 更新效果和类组件是一样的,但是 useState 有一点需要注意的是,就是当调用改变 state 的 dispatch 时候,在本次函数的执行上下文中,是获取不到最新的 state 值,举例如下</p>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line">[number, setNumber] = <span class="title class_">React</span>.<span class="title function_">useState</span>(<span class="number">0</span>);</span><br><span class="line">handleClick = <span class="function">() =&gt;</span> &#123;</span><br><span class="line">  <span class="built_in">setTimeout</span>(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">    <span class="title function_">setNumber</span>(<span class="number">1</span>);</span><br><span class="line">    <span class="variable language_">console</span>.<span class="title function_">log</span>(number);</span><br><span class="line">  &#125;);</span><br><span class="line">  <span class="title function_">setNumber</span>(<span class="number">2</span>);</span><br><span class="line">  <span class="variable language_">console</span>.<span class="title function_">log</span>(number);</span><br><span class="line">  <span class="title class_">ReactDom</span>.<span class="title function_">flushSync</span>(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">    <span class="title function_">setNumber</span>(<span class="number">3</span>);</span><br><span class="line">    <span class="variable language_">console</span>.<span class="title function_">log</span>(number);</span><br><span class="line">  &#125;);</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>

<p>&emsp;打印的结果都是为 0,原因很简单,<font color="black" size="3">函数组件就是函数的执行,在函数的执行过程中,函数内部变量重新声明,所以改变的 state,只有在下一次函数组件执行时才会更新</font></p>
<h2 id="类组件中的-setState-和函数-useState-有什么异同"><a href="#类组件中的-setState-和函数-useState-有什么异同" class="headerlink" title="类组件中的 setState 和函数 useState 有什么异同"></a>类组件中的 setState 和函数 useState 有什么异同</h2><p>&emsp;<font color="black" size="3">相同点</font></p>
<ul>
<li>首先从原理角度出发,setState 和 useState 都触发了更新视图,底层都调用了<font color="red">scheduleUpdateOnFiber</font><br>方法,而且事件驱动都有批量更新原规则。</li>
</ul>
<p>&emsp;<font color="black" size="3">不同点</font></p>
<ul>
<li>在不是 pureComponent 组件模式下,setState 不会进行两次 state 值的浅比较,只要调用 setState,在没有其他的优化前提下,就会执行更新。但是 useState 中会默认比较两次 state 是否相同,然后决定更新组件</li>
<li>setState 有专门监听 state 变化的回调函数 callback,可以获取最新的 state,但是在函数组件中,只能通过 useEffect 传入 state 作为第二个参数,来监听 state 的变化</li>
<li>setState 在底层处理逻辑上主要是和老 state 进行合并处理(类似于{…state,…newState}),而 useState 中更倾向于重新复制(dispatch&#x3D;&gt;newState)</li>
</ul>
<h2 id="总结"><a href="#总结" class="headerlink" title="总结"></a><font color="red">总结</font></h2><p>&emsp;学习到了什么?</p>
<ul>
<li>setState 的用法详解,底层更新流程</li>
<li>useState 的用法详解,底层更新流程,以及更新注意事项</li>
<li>提供优先级的使用方法和打破批量更新规则的使用方法</li>
</ul>
</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta"><i class="fas fa-circle-user fa-fw"></i>文章作者: </span><span class="post-copyright-info"><a href="https://leachliu.gitee.io">刘超</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta"><i class="fas fa-square-arrow-up-right fa-fw"></i>文章链接: </span><span class="post-copyright-info"><a href="https://leachliu.gitee.io/2021/12/30/react/class%E4%B8%AD%E7%9A%84state%E5%92%8Chooks%E4%B8%AD%E7%9A%84state/">https://leachliu.gitee.io/2021/12/30/react/class%E4%B8%AD%E7%9A%84state%E5%92%8Chooks%E4%B8%AD%E7%9A%84state/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta"><i class="fas fa-circle-exclamation fa-fw"></i>版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="https://leachliu.gitee.io" target="_blank">刘超的博客</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/state/">state</a></div><div class="post_share"><div class="social-share" data-image="/images/avatar.webp" data-sites="facebook,twitter,wechat,weibo,qq"></div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/js/social-share.min.js" defer></script></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/2022/01/05/react/%E5%A4%9A%E5%8A%9F%E8%83%BDRef/" title="多功能Ref"><div class="cover" style="background: var(--default-bg-color)"></div><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">多功能Ref</div></div></a></div><div class="next-post pull-right"><a href="/2021/12/29/react/react-router%E7%9A%84%E6%B8%B2%E6%9F%93/" title="react-router路由鉴权(React项目搭建5)"><div class="cover" style="background: var(--default-bg-color)"></div><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">react-router路由鉴权(React项目搭建5)</div></div></a></div></nav></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="is-center"><div class="avatar-img"><img src="/images/avatar.webp" onerror="this.onerror=null;this.src='/img/friend_404.gif'" alt="avatar"/></div><div class="author-info__name">刘超</div><div class="author-info__description">只有自己强大，才不会被别人践踏。</div></div><div class="card-info-data site-data is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">41</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">21</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">6</div></a></div><a id="card-info-btn" target="_blank" rel="noopener" href="https://github.com/xxxxxx"><i class="fab fa-github"></i><span>Follow Me</span></a><div class="card-info-social-icons is-center"><a class="social-icon" href="http://wpa.qq.com/msgrd?v=3&amp;uin=923946406&amp;site=qq&amp;menu=yes" target="_blank" title="QQ"><i class="fab fa-qq"></i></a><a class="social-icon" href="https://chao-picture-bed.oss-cn-hangzhou.aliyuncs.com/blog/vue/popperJs/202301131417748.jpg" target="_blank" title="Wechat"><i class="fab fa-weixin"></i></a><a class="social-icon" href="/923946406@qq.com" target="_blank" title="Email"><i class="fas fa-envelope"></i></a><a class="social-icon" href="https://github.com/tzy13755126023" target="_blank" title="Github"><i class="fab fa-github"></i></a><a class="social-icon" href="/atom.xml" target="_blank" title="Rss"><i class="fas fa-rss"></i></a></div></div><div class="card-widget card-announcement"><div class="item-headline"><i class="fas fa-bullhorn fa-shake"></i><span>公告</span></div><div class="announcement_content">书山有路勤为径,学海无涯苦作舟</div></div><div class="card-widget tzy-right-widget" id="card-wechat"><div id="flip-wrapper"><div id="flip-content"><div class="face"></div><div class="back face"></div></div></div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span><span class="toc-percentage"></span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E7%B1%BB%E7%BB%84%E4%BB%B6%E4%B8%AD%E7%9A%84-state"><span class="toc-number">1.</span> <span class="toc-text">类组件中的 state</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#setState-%E7%9A%84%E7%94%A8%E6%B3%95"><span class="toc-number">1.1.</span> <span class="toc-text">setState 的用法</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%81%87%E8%AE%BE%E4%B8%80%E4%BB%B6%E4%BA%8B%E4%BB%B6%E4%B8%AD%E8%A7%A6%E5%8F%91%E4%BA%86%E4%B8%80%E6%AC%A1%E5%A6%82%E4%B8%8A-setState-%E5%9C%A8-React-%E5%BA%95%E5%B1%82%E5%88%B0%E5%BA%95%E5%81%9A%E4%BA%86%E5%86%99%E4%BB%80%E4%B9%88%E4%BA%8B%E6%83%85"><span class="toc-number">1.2.</span> <span class="toc-text">假设一件事件中触发了一次如上 setState,在 React 底层到底做了写什么事情?</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E7%B1%BB%E7%BB%84%E4%BB%B6%E5%A6%82%E4%BD%95%E9%99%90%E5%88%B6-state-%E6%9B%B4%E6%96%B0%E8%A7%86%E5%9B%BE"><span class="toc-number">1.3.</span> <span class="toc-text">类组件如何限制 state 更新视图</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link"><span class="toc-number">1.3.1.</span> <span class="toc-text">对于类组件如何限制state更新作用呢?</span></a></li></ol></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#setState-%E5%8E%9F%E7%90%86"><span class="toc-number">2.</span> <span class="toc-text">setState 原理</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#legacy%E6%A8%A1%E5%BC%8F%E4%B8%8B%E7%9A%84%E5%8F%AF%E6%8E%A7%E4%BB%BB%E5%8A%A1%E5%92%8C%E9%9D%9E%E6%8E%A7%E4%BB%BB%E5%8A%A1"><span class="toc-number">3.</span> <span class="toc-text">legacy模式下的可控任务和非控任务</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link"><span class="toc-number">3.0.1.</span> <span class="toc-text">所以批量更新规则被打破。</span></a></li><li class="toc-item toc-level-4"><a class="toc-link"><span class="toc-number">3.0.2.</span> <span class="toc-text">那么如何在异步环境下,继续开启批量更新模式</span></a></li></ol></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%87%BD%E6%95%B0%E7%BB%84%E4%BB%B6%E4%B8%AD%E7%9A%84-state"><span class="toc-number">4.</span> <span class="toc-text">函数组件中的 state</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#useStete-%E7%9A%84%E7%94%A8%E6%B3%95"><span class="toc-number">4.1.</span> <span class="toc-text">useStete 的用法</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%9F%BA%E6%9C%AC%E7%94%A8%E6%B3%95"><span class="toc-number">4.1.1.</span> <span class="toc-text">基本用法</span></a></li></ol></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%A6%82%E4%BD%95%E7%9B%91%E5%90%AC-state-%E5%8F%98%E5%8C%96"><span class="toc-number">5.</span> <span class="toc-text">如何监听 state 变化</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#dispatch%E6%9B%B4%E6%96%B0%E7%89%B9%E7%82%B9"><span class="toc-number">6.</span> <span class="toc-text">dispatch更新特点</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E7%B1%BB%E7%BB%84%E4%BB%B6%E4%B8%AD%E7%9A%84-setState-%E5%92%8C%E5%87%BD%E6%95%B0-useState-%E6%9C%89%E4%BB%80%E4%B9%88%E5%BC%82%E5%90%8C"><span class="toc-number">7.</span> <span class="toc-text">类组件中的 setState 和函数 useState 有什么异同</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%80%BB%E7%BB%93"><span class="toc-number">8.</span> <span class="toc-text">总结</span></a></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/2023/11/06/comlibary/4.%E7%BB%84%E4%BB%B6%E5%BA%93%E7%B1%BB%E5%90%8D%E6%96%B9%E6%B3%95%E5%AE%9E%E7%8E%B0%E4%BB%A5%E5%8F%8A%E8%A7%84/" title="无题">无题</a><time datetime="2023-11-06T07:16:00.298Z" title="发表于 2023-11-06 15:16:00">2023-11-06</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2023/11/06/comlibary/3.%E6%90%AD%E5%BB%BA%E7%BB%84%E4%BB%B6%E5%BA%93%E5%BC%80%E5%8F%91%E7%8E%AF%E5%A2%83/" title="组件库框架 - 3 搭建组件库开发环境"><img src="/images/beijing4.webp" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="组件库框架 - 3 搭建组件库开发环境"/></a><div class="content"><a class="title" href="/2023/11/06/comlibary/3.%E6%90%AD%E5%BB%BA%E7%BB%84%E4%BB%B6%E5%BA%93%E5%BC%80%E5%8F%91%E7%8E%AF%E5%A2%83/" title="组件库框架 - 3 搭建组件库开发环境">组件库框架 - 3 搭建组件库开发环境</a><time datetime="2023-11-06T06:30:00.000Z" title="发表于 2023-11-06 14:30:00">2023-11-06</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2023/11/06/comlibary/2.%E5%88%9D%E5%A7%8B%E5%8C%96workspace-root/" title="组件库框架 - 2 初始化workspace-root"><img src="/images/beijing4.webp" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="组件库框架 - 2 初始化workspace-root"/></a><div class="content"><a class="title" href="/2023/11/06/comlibary/2.%E5%88%9D%E5%A7%8B%E5%8C%96workspace-root/" title="组件库框架 - 2 初始化workspace-root">组件库框架 - 2 初始化workspace-root</a><time datetime="2023-11-06T03:18:00.000Z" title="发表于 2023-11-06 11:18:00">2023-11-06</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2023/10/27/comlibary/1.%E6%90%AD%E5%BB%BApnpm%E3%80%81monorepo/" title="组件库框架 - 1 搭建pnpn monorepo"><img src="/images/beijing3.webp" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="组件库框架 - 1 搭建pnpn monorepo"/></a><div class="content"><a class="title" href="/2023/10/27/comlibary/1.%E6%90%AD%E5%BB%BApnpm%E3%80%81monorepo/" title="组件库框架 - 1 搭建pnpn monorepo">组件库框架 - 1 搭建pnpn monorepo</a><time datetime="2023-10-27T06:36:00.000Z" title="发表于 2023-10-27 14:36:00">2023-10-27</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2023/01/12/other/%E4%BD%BF%E7%94%A8OSS+PicGo%E6%90%AD%E5%BB%BA%E5%9B%BE%E5%BA%8A/" title="使用OSS+PicGo搭建图床"><img src="https://chao-picture-bed.oss-cn-hangzhou.aliyuncs.com/blog/vue/popperJs/202301121557184.png" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="使用OSS+PicGo搭建图床"/></a><div class="content"><a class="title" href="/2023/01/12/other/%E4%BD%BF%E7%94%A8OSS+PicGo%E6%90%AD%E5%BB%BA%E5%9B%BE%E5%BA%8A/" title="使用OSS+PicGo搭建图床">使用OSS+PicGo搭建图床</a><time datetime="2023-01-12T07:39:00.000Z" title="发表于 2023-01-12 15:39:00">2023-01-12</time></div></div></div></div></div></div></main><footer id="footer"><div id="footer-wrap"><div class="copyright">&copy;2020 - 2023  <i id="heartbeat" class="fa fas fa-heartbeat"></i> 刘超</div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside-config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><button id="go-up" type="button" title="回到顶部"><span class="scroll-percent"></span><i class="fas fa-arrow-up"></i></button></div></div><div><script src="/js/utils.js"></script><script src="/js/main.js"></script><script src="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox/fancybox.umd.min.js"></script><div class="js-pjax"></div><canvas id="universe"></canvas><script defer src="/js/universe.js"></script><script defer src="https://fastly.jsdelivr.net/npm/hexo-theme-volantis@latest/source/js/issues.min.js"></script><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script><div id="algolia-search"><div class="search-dialog"><nav class="search-nav"><span class="search-dialog-title">搜索</span><button class="search-close-button"><i class="fas fa-times"></i></button></nav><div class="search-wrap"><div id="algolia-search-input"></div><hr/><div id="algolia-search-results"><div id="algolia-hits"></div><div id="algolia-pagination"></div><div id="algolia-info"><div class="algolia-stats"></div><div class="algolia-poweredBy"></div></div></div></div></div><div id="search-mask"></div><script src="https://cdn.jsdelivr.net/npm/algoliasearch/dist/algoliasearch-lite.umd.min.js"></script><script src="https://cdn.jsdelivr.net/npm/instantsearch.js/dist/instantsearch.production.min.js"></script><script src="/js/search/algolia.js"></script></div></div><!-- hexo injector body_end start --><script async src="//at.alicdn.com/t/font_2032782_8d5kxvn09md.js"></script><!-- hexo injector body_end end --></body></html>